package com.pda.smallbug.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.pda.smallbug.myapplication.httpDomain.LoginHttp;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2017/6/27.
 */

public class LoginActivity extends Activity implements View.OnClickListener{
    private Spinner spinner;
    private PopupWindow popupWindow;
    private LinearLayout name_layout;
    private RecyclerView recyclerView;
    private ImageView name_icon;
    private List<LoginHttp.LoginData> data;
    private LoginAdapter adapter;
    private int selectPosition=0;
    private TextView name;
    private EditText editText;
    private Button login;
    private TextView system;
    private TextView reset;
    private boolean loginflag=false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        EventBus.getDefault().register(this);
        name_layout=(LinearLayout)findViewById(R.id.name_layout);
        name=(TextView)findViewById(R.id.name);
        name_icon=(ImageView) findViewById(R.id.name_icon);
        editText=(EditText)findViewById(R.id.editText);
        login=(Button)findViewById(R.id.login);
        system=(TextView)findViewById(R.id.system);
        reset=(TextView)findViewById(R.id.reset);
        setPopupWindow();
        addListener();
        initData();
    }

    private void addListener(){
        name_layout.setOnClickListener(this);
        login.setOnClickListener(this);
        system.setOnClickListener(this);
        reset.setOnClickListener(this);
    }

    private void initData(){
        String username=MyApplication.mySharedPreferences.getString("username","");
        if (!username.isEmpty()){
            name.setText(username);
        }

        if (MyApplication.mySharedPreferences.getString("url","").isEmpty()){
            Toast.makeText(LoginActivity.this,"请设置服务器ip",Toast.LENGTH_SHORT).show();
            Intent intent=new Intent(LoginActivity.this,SystemAcitvity.class);
            startActivity(intent);
            loginflag=false;
        }else {
            getData();
        }
    }

    private void getData(){
        loginflag=false;
        RequestParams requestParams=new RequestParams(MyApplication.url+"tools/submit_ajax.ashx?action=getuserlist");
        requestParams.setConnectTimeout(1000);
        x.http().post(requestParams, new Callback.CacheCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("asd",result);
                Gson gson=new Gson();
                LoginHttp http= gson.fromJson(result,LoginHttp.class);
                if (http.getStatus()==1){
                    data=http.getData();
                    adapter.update(data);
                    loginflag=true;
                    for (LoginHttp.LoginData i :data) {
                        if (i.getFusername().equals(name.getText().toString())){
                            selectPosition=data.indexOf(i);
                        }
                    }
                }else {
                    Toast.makeText(LoginActivity.this,http.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(LoginActivity.this,"网络请求失败，请检查服务器ip",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public boolean onCache(String result) {
                return false;
            }
        });
    }
    private void setPopupWindow(){
        View contentView = LayoutInflater.from(LoginActivity.this).inflate(R.layout.poplayout, null);
        recyclerView=(RecyclerView)contentView.findViewById(R.id.recyclerView);
        adapter=new LoginAdapter(this);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(LoginActivity.this,LinearLayoutManager.VERTICAL,false));
        popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT,  300, true);
        popupWindow.setTouchable(true);
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.color.transpant));
        // 设置好参数之后再show

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                name_icon.setImageResource(R.mipmap.login_xia);
            }
        });

    }

    public void onEventMainThread(MyEvent event)
    {
        if (event.getCode()==0){
            getData();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View view) {
        int id=view.getId();
        switch (id){
            case R.id.name_layout:
                if (!loginflag){
                    Toast.makeText(LoginActivity.this,"服务器ip不正确，请重新设置",Toast.LENGTH_SHORT).show();
                    return;
                }
                popupWindow.showAsDropDown(name_layout,0,0);
                name_icon.setImageResource(R.mipmap.login_shang);
                break;
            case R.id.login:
                if (!loginflag){
                    Toast.makeText(LoginActivity.this,"服务器ip不正确，请重新设置",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (name.getText().toString().equals("请选择用户名")){
                    Toast.makeText(LoginActivity.this,"请选择用户名",Toast.LENGTH_SHORT).show();
                }else if (editText.getText().toString().isEmpty()){
                    Toast.makeText(LoginActivity.this,"请输入密码",Toast.LENGTH_SHORT).show();
                }else if (editText.getText().toString().equals(data.get(selectPosition).getFpsd())){
                    Toast.makeText(LoginActivity.this,"登陆成功",Toast.LENGTH_SHORT).show();
                    Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                    SharedPreferences.Editor edit = MyApplication.mySharedPreferences.edit();
                    edit.putString("id", String.valueOf(data.get(selectPosition).getFItemID()));
                    edit.putString("username",data.get(selectPosition).getFusername());
                    edit.commit();
                }else {
                    Toast.makeText(LoginActivity.this,"密码错误",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.system:
                Intent intent=new Intent(LoginActivity.this,SystemAcitvity.class);
                startActivity(intent);
                break;
            case R.id.reset:
                if (!loginflag){
                    Toast.makeText(LoginActivity.this,"服务器ip不正确，请重新设置",Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent2=new Intent(LoginActivity.this,ResetActivity.class);
                startActivity(intent2);
                break;
        }
    }

    public void select(int position) {
        selectPosition=position;
        name.setText(data.get(position).getFusername());
        popupWindow.dismiss();
    }
}
